package com.example.shiro.demo.exception;

import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***

 * @author renweiping
 * @description controller统一异常处理
 * @date    2019/9/18

 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 其他异常处理
     *
     * @param ex 其他异常处理
     * @return Result<String>
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Map<String,Object> invoke(Exception ex) {
        ex.printStackTrace();
        log.error(ex.getLocalizedMessage());
        Map<String,Object> result = new HashMap<>();
        result.put("msg",ex.getLocalizedMessage());
        return result;

    }

    /**
     * 参数绑定异常处理
     *
     * @param ex 参数绑定异常
     * @return Result<Map<String, String>>
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Map<String, Object> invoke(BindException ex) {
        Map<String, Object> data = new HashMap<>(10);
        for (ObjectError error : ex.getAllErrors()) {
            data.put(((FieldError) error).getField(), error.getDefaultMessage());
        }
        return data;

    }



    /**
     * 参数绑定异常处理
     *
     * @param ex 参数绑定异常
     * @return Result<Map<String, String>>
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Map<String, String> invoke(MethodArgumentNotValidException ex) {
        Map<String, String> data = new HashMap<>(10);
        List<FieldError> bindingResult = ex.getBindingResult().getFieldErrors();
        if (bindingResult!=null && !bindingResult.isEmpty()){
            data.put(bindingResult.get(0).getField(), bindingResult.get(0).getDefaultMessage());
        }
        return data;

    }



    /**
     * 无权限异常
     *
     * @param ex 参数绑定异常
     * @return Result<Map<String, String>>
     */
    @ExceptionHandler(AuthorizationException.class)
    @ResponseBody
    public Map<String, String> invoke(AuthorizationException ex) {
        Map<String, String> data = new HashMap<>(10);
        log.error(ex.getLocalizedMessage());
        log.error(ex.getMessage());
        ex.printStackTrace();
        if (ex != null){
            data.put("msg", ex.getLocalizedMessage());
        }
        return data;

    }


}
